package cn.xiaolang.function.data_structure;

import com.google.common.collect.Lists;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 两数之和
 *
 * @author fuhw/Dean
 * @date 2020-04-08
 */
public class ArrayEleForSum {


    public static void main(String[] args) {
        int[] arr = new int[]{1, 6, 2, 3, 3, 4, 8};
        int sumValue = 7;

        towSum2(arr, sumValue);

    }

    /**
     * 思路: hash存储diff-index，校验数据中元素在hash表中
     * O(2n)
     *
     * @param arr
     * @param sumValue
     */
    private static void towSum2(int[] arr, int sumValue) {
        // diff-index
        Map<Integer, Integer> map = new HashMap<>();

        // O(n)
        for (int i = 0; i < arr.length; i++) {
            map.put(sumValue - arr[i], i);
        }

        // O(n)
        for (int i = 0; i < arr.length; i++) {
            // O(1) 避免 2*ele = sumValue
            if (map.containsKey(arr[i]) && i != map.get(arr[i])) {
                System.out.println(map.get(arr[i]) + "====" + i);
            }
        }
    }


    /**
     * 思路：按指定和的值-数据的元素，看是否在数组中
     * O(n2)
     *
     * @param arr
     * @param sumValue
     */
    private static void towSum1(int[] arr, int sumValue) {
        List<Integer> integers = Lists.newArrayList();
        // O(n)
        for (int i = 0; i < arr.length; i++) {
            integers.add(arr[i]);
        }

        // O(n)
        for (int i = 0; i < arr.length; i++) {
            int diff = sumValue - arr[i];
            // O(n)
            if (integers.contains(diff)) {
                System.out.println(i + "===" + integers.indexOf(diff));
            }
        }
    }


}
